<?php
apf_require_controller("APF_Resource_Resources");

class APF_Resource_CompressedResourcesController extends APF_Resource_ResourcesController {
    const CONFIG_N_YUICOMPRESSOR_HOST = "yuicompressor_host";
    const CONFIG_N_YUICOMPRESSOR_PORT = "yuicompressor_port";

    // Override
    public function handle_request() {
        ob_start();
        parent::handle_request();

        $uri = $_SERVER['REQUEST_URI'];
        $content = ob_get_contents();
        ob_end_clean();

        $apf = APF::get_instance();
        $host = @$apf->get_config(self::CONFIG_N_YUICOMPRESSOR_HOST, parent::CONFIG_F_RESOURCE);
        $port = @$apf->get_config(self::CONFIG_N_YUICOMPRESSOR_PORT, parent::CONFIG_F_RESOURCE);

        if (!$host || !$port) {
            echo $content;
            return;
        }

        $fp = @fsockopen($host, $port);
        if (!$fp) {
            echo $content;
            return;
        }

        fwrite($fp, "$uri\n");
        fwrite($fp, $content);
        fwrite($fp, "\n\0\n");
        while (!feof($fp)) {
            echo fread($fp, 8192);
        }

        fclose($fp);
    }
}
?>